<?php

namespace App\Admin\Controllers;

use App\Models\NewBookRecommend;

use App\Models\Product;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use App\Admin\Extensions\Tools\Button;

class NewBookRecommendController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('新书推荐');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('新书推荐');
            $content->description('编辑');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('新书推荐');
            $content->description('新建');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(NewBookRecommend::class, function (Grid $grid) {
            $grid->disableExport();
            $grid->model()->with('product')->whereHas('product', function (){});

            $grid->column('pid', '书籍ID(点击跳转到该书)')->display(function($pid) {
                return '<a target="_blank" href="' . route('productInfo', ['uuid' => $this->product['uuid']]) .'">' . $pid . '</a>';
            });
            $grid->extra('书名')->display(function($extra) {
                return $this->product['name'];
            });
            $grid->disableExport();
            $grid->model()->orderBy('created_at','desc');

            $grid->created_at('创建时间');
            $grid->updated_at('最后修改');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(NewBookRecommend::class, function (Form $form) {

            $form->text('pid','书籍ID')->help('填写已在产品管理发布的书籍ID');

            $form->button();
            $form->embeds('extra', '书籍信息', function ($form) {
                $form->text('name','书籍名')->help('查询出来对应书籍ID的书籍名');
            });
                
            $form->display('created_at', '添加时间');
            $form->display('updated_at', '最近更新');
        });
    }
}
